﻿namespace Mueller.ScriptTools

open System
open System.Reflection
open System.IO
open V8Bridge.FSharp

module private CompilerTools =
    
    let getResource name =
        use stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(name)
        use reader = new StreamReader(stream)
        reader.ReadToEnd()

    let init script =
        getResource script
        |> ScriptEngine.initializeLibrary
        |> Async.RunSynchronously


open CompilerTools

/// CoffeeScript compiler.
/// http://coffeescript.org/
type CoffeeScriptCompiler() =
    static let loadLibrary = lazy( init "coffee-script.js" )

    member x.Compile wrap code =
        loadLibrary.Force()
        ScriptEngine.callFunction (if wrap then "compile_wrapped" else "compile_bare") code

/// Iced CoffeeScript compiler.
/// http://maxtaco.github.com/coffee-script/
type IcedCompiler() =
    static let loadLibrary = lazy( init "coffee-script-iced.js" )

    member x.Compile wrap code =
        loadLibrary.Force()
        ScriptEngine.callFunction (if wrap then "compile_wrapped" else "compile_bare") code

/// Uglify JS minifier.
/// https://github.com/mishoo/UglifyJS
type UglifyCompiler() =
    static let loadLibrary = lazy( init "uglify.js" )

    member x.Compile code =
        loadLibrary.Force()
        async {
            let! result = ScriptEngine.callFunction "compilify_ujs" code
            match result with
            | Fail x -> return Fail x
            | Success minified ->
                if minified.StartsWith "Unexpected" then
                    return Fail minified
                else
                    return Success minified
        }

